<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;
use app\model\Expand;
use app\model\Campaign;

class FeedCopy extends Common
{

	public function read(Request $request)
	{
		if($this->hasPermission($request->sessInfo, 'feedcopy:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		if( in_array($sort, ['impression', 'clicks', 'cost', 'cash', 'rebate', 'copynumber', 'cpc', 'ctr', 'copycost']) ) {
			$sort = 's.'.$sort;
		} else {
			$sort = 'a.'.$sort;
		}

		array_push( $where, ['a.companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['a.userType', '=', 2 ] );

		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['a.bazaarId', '=',  $bazaarId ] );
		}

		$userid = $request->param('userid', '', 'trim');
		if($userid) {
			array_push( $where, ['a.userid', '=',  $userid ] );
		}

 		$campaignId = $request->param('campaignId', '', 'trim');
		if($campaignId) {
			array_push( $where, ['a.campaignId', 'in',  $campaignId ] );
		}

		$createTimeStart = $request->param('createTimeStart', '', 'trim');
		$createTimeEnd = $request->param('createTimeEnd', '', 'trim');
		if( $createTimeStart && $createTimeEnd ) {
			$time = cloud_datetime_format( $createTimeStart, $createTimeEnd, true);
		} else {
			$time = cloud_datetime_format( date('Y-m-d 00:00:00'), date('Y-m-d 00:00:00', strtotime("+1 day")), true);
		}

    $search = [];
		array_push( $search, " s.companyId = {$request->sessInfo['companyId']} ");
		array_push( $search, " s.userType = 2 ");
		array_push( $search, " s.adgroupid > 0 ");
		array_push( $search, " a.adgroupId = s.adgroupid ");
	  array_push( $search, " s.datatime BETWEEN {$time[0]} AND {$time[1]} ");
    //权限管理
		$roleTempId = Db::table('cfg_user')->where('id', $request->sessInfo['id'])->value('role');
		if($roleTempId) {
			$authaccount = Db::table('cfg_role')->where('companyId', $request->sessInfo['companyId'])->where('id', $roleTempId)->value('feedauthaccount');
			if($authaccount) {
				array_push( $where, ['a.userid', 'in',  $authaccount ] );
			}
		}
 		$query = Db::table('cfg_adgroup')
		->alias('a')
		->field('a.userId, a.bazaarId, a.campaignName, a.adgroupName,
		  sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
			IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->group('a.adgroupId')
		->order($sort, $order)
		->paginate($limit);

    $count = $query->total();
		$items = $query->items();
		foreach($items as &$value ) {
			$value['impression'] = $value['impression'] ? $value['impression'] : 0;
			$value['clicks'] = $value['clicks'] ? $value['clicks'] : 0;
			$value['cost'] = $value['cost'] ? $value['cost'] : 0;
			$value['cash'] = $value['cash'] ? $value['cash'] : 0;
			$value['rebate'] = $value['rebate'] ? $value['rebate'] : 0;
			$value['cpc'] = $value['cpc'] ? $value['cpc'] : 0;
			$value['ctr'] = $value['ctr'] ? $value['ctr'] : 0;
			$value['copynumber'] = $value['copynumber'] ? $value['copynumber'] : 0;
			$value['copycost'] = $value['copycost'] ? $value['copycost'] : 0;
		}

		$total = Db::table('cfg_adgroup')
		->alias('a')
		->field('sum(s.impression) as impression,
			sum(s.clicks) as clicks,
			sum(s.cost) as cost,
			sum(s.cash) as cash,
			avg(s.rebate) as rebate,
			sum(s.copynumber) as copynumber,
			ROUND( sum(`cost`) / sum(`clicks`), 2) as `cpc`,
			ROUND( sum(`clicks`) / sum(`impression`) * 100, 2) as `ctr`,
	 		IF(ROUND( sum(`cost`) / sum(`copynumber`), 2 ), ROUND( sum(`cost`) / sum(`copynumber`), 2 ), sum(`cost`)) as `copycost`')
	  ->leftJoin('cfg_search s', implode(' AND ', $search))
		->where($where)
		->find();

		$total['impression'] = $total['impression'] ? $total['impression'] : 0;
		$total['clicks'] = $total['clicks'] ? $total['clicks'] : 0;
		$total['cost'] = $total['cost'] ? $total['cost'] : 0;
		$total['cash'] = $total['cash'] ? $total['cash'] : 0;
		$total['rebate'] = $total['rebate'] ? $total['rebate'] : 0;
		$total['cpc'] = $total['cpc'] ? $total['cpc'] : 0;
		$total['ctr'] = $total['ctr'] ? $total['ctr'] : 0;
		$total['copynumber'] = $total['copynumber'] ? $total['copynumber'] : 0;
		$total['copycost'] = $total['copycost'] ? $total['copycost'] : 0;

		return ['code'=> 0, 'msg'=> '', 'count'=> $count, 'data'=> $items, 'total' => $total,
			'expand' => Expand::getList($request->sessInfo, 2),
			'bazaar' => Bazaar::getList($request->sessInfo, 2) ];
	}

	public function getCampaign(Request $request) {
		$userid = $request->param('userid', '', 'trim');
		if( empty($userid)) {
			return ['code'=> 0, 'campaign'=> [] ];
		}
		return ['code'=> 0, 'campaign'=> Campaign::getList($request->sessInfo, $userid)];
	}

}
